const db = require('./db.js')
const moment = require('moment')

exports.addTopic = async (body) => {
	try {
		const curTime = moment().format('YYYY-MM-DD hh:mm:ss')
		const strSql = `
			insert into topics (title,content,user_id,create_time,modify_time) 
			values (
				'${body.title}',
				'${body.content}',
				'${body.user_id}',
				'${curTime}',
				'${curTime}'
			)
		`
		const ret = await db.query(strSql)
		return ret.insertId
	} catch(err) {
		throw err
	}
}

exports.getTopic = async (id) => {
	try {
		const strSql = `
			select * from topics where id='${id}'
		`
		const [topic] = await db.query(strSql)
		return topic
	} catch(err) {
		throw err
	}
}

exports.getTopics = async (query) => {
	try {
		let {_page = 1, _limit = 20} = query
		if (_page < 1) {
			_page = 1
		}
		if (_limit < 1) {
			_limit = 1
		}
		if (_limit > 20) {
			_limit =20
		}
		const _start = (_page - 1) * _limit
		const strSql = `
			select * from topics order by id desc limit ${_start} , ${_limit}
		`
		const topics = await db.query(strSql)

		const strSql2 = `select count(1) count from topics`
		const [{count}] = await db.query(strSql2)
		return {topics, count}
	} catch(err) {
		throw err
	}
}

exports.editTopic = async (body) => {
	try {
		const modify_time = moment().format('YYYY-MM-DD hh:mm:ss')
		const strSql = `
			update topics set title='${body.title}',content='${body.content}',modify_time='${modify_time}' where id=${body.id}
		`
		const ret = await db.query(strSql)
		return ret
	} catch(err) {
		throw err
	}
}

exports.deleteById = async (id) => {
	try {
		const strSql = `
			delete from topics where id=${id}
		`
		const ret = await db.query(strSql)
		return ret
	} catch(err) {
		throw err
	}
}